<!-- 时间段 -->
<template>
    <div>
        <el-form-item :label="$t('禁止下载时间段')" style="font-weight:600;">
        </el-form-item>
        <el-form-item>
            <!-- <el-time-select style="width:142px" v-model="start" :picker-options="{start: '00:00', step: '00:05', end: '23:55'}" :placeholder="$t('请选择开始时间')" filterable></el-time-select> -->
            <el-select v-model="start" :placeholder="$t('请选择开始时间')" size="small" style="width:142px" filterable remote>
                <template slot="prefix"><i class="el-icon-time" style="padding: 5px;margin-top: 3.5px;" /></template>
                <el-option v-for="(item, index) in timeSlotArray" :key="index" :label="item.name" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
       <el-form-item>{{ $t('至') }}</el-form-item>
        <el-form-item>
            <!-- <el-time-select style="width:142px" v-model="end" :picker-options="{start: '00:00', step: '00:05', end: '23:55', minTime: start}" :placeholder="$t('请选择结束时间')" filterable></el-time-select> -->
            <el-select v-model="end" :placeholder="$t('请选择结束时间')" size="small" style="width:142px" filterable remote>
                <template slot="prefix"><i class="el-icon-time" style="padding: 5px;margin-top: 3.5px;" /></template>
                <el-option v-for="(item, index) in endTimeSlotArray" :key="index" :label="item.name" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-select v-model="week" :placeholder="$t('选择周期')" size="small" multiple collapse-tags @change="weekChange('downloads')" style="width: 161px">
                <el-option v-for="(item, index) in weeks" :key="index" :label="$t(item.name)" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <bs-add-button-icon :show-icon="false" @click.native="doAddWeekInfo('downloads')"></bs-add-button-icon>
            <bs-delete-button-icon :show-icon="false" @click.native="deleteRow('downloads')"></bs-delete-button-icon>
            <bs-clean-button-icon @click.native="deleteAll('downloads')"></bs-clean-button-icon>
        </el-form-item>
        <el-row>
            <el-col :span="24">
                 <el-form-item>
                    <el-table ref="table" :data="tableData" style="width: 100%;border:1px solid #e9e9e9;border-bottom:0;" :show-header="false" height="127px" @selection-change="handleSelectionDownloadsChange" @row-click="getCurrentRow">
                    <!-- <el-table :data="tableData" style="width: 100%;width: 100%;border:1px solid #e9e9e9;border-bottom:0;" :show-header="false" height="543px"> -->
                        <el-table-column type="selection" width="40px"></el-table-column>
                        <el-table-column prop="timeinfo" width="100px"></el-table-column>
                        <el-table-column prop="weekinfo"></el-table-column>
                    </el-table>
                 </el-form-item>
            </el-col>
        </el-row>

        <el-form-item :label="$t('终端开关机时间')" style="font-weight:600;">
        </el-form-item>
        <el-form-item>
            <!-- <el-time-select style="width:142px" v-model="forbidStart" :picker-options="{start: '00:00', step: '00:05', end: '23:55'}" :placeholder="$t('请选择开始时间')"></el-time-select> -->
            <el-select v-model="forbidStart" :placeholder="$t('请选择开始时间')" size="small" style="width:142px" filterable remote>
                <template slot="prefix"><i class="el-icon-time" style="padding: 5px;margin-top: 3.5px;" /></template>
                <el-option v-for="(item, index) in timeSlotArray" :key="index" :label="item.name" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>{{ $t('至') }}</el-form-item>
        <el-form-item>
            <!-- <el-time-select style="width:142px" v-model="forbidEnd" :picker-options="{start: '00:00', step: '00:05', end: '23:55', minTime: forbidStart}" :placeholder="$t('请选择结束时间')"></el-time-select> -->
            <el-select v-model="forbidEnd" :placeholder="$t('请选择结束时间')" size="small" style="width:142px" filterable remote>
                <template slot="prefix"><i class="el-icon-time" style="padding: 5px;margin-top: 3.5px;" /></template>
                <el-option v-for="(item, index) in forbidEndTimeSlotArray" :key="index" :label="item.name" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-select v-model="forbidWeek" :placeholder="$t('选择周期')" size="small" multiple collapse-tags @change="weekChange('onoffs')" style="width: 161px">
                <el-option v-for="(item, index) in weeks" :key="index" :label="$t(item.name)" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <bs-add-button-icon :show-icon="false" @click.native="doAddWeekInfo('onoffs')"></bs-add-button-icon>
            <bs-delete-button-icon :show-icon="false" @click.native="deleteRow('onoffs')"></bs-delete-button-icon>
            <bs-clean-button-icon @click.native="deleteAll('onoffs')"></bs-clean-button-icon>
        </el-form-item>
        <el-row>
            <el-col :span="24">
                <el-table ref="forbidTable" :data="forbidTableData" style="border:1px solid #e9e9e9;border-bottom:0;margin-bottom:10px;width: 100%;" :show-header="false" height="127px" @selection-change="handleSelectionOnoffsChange" @row-click="getCurrentRow">
                    <el-table-column type="selection" width="40px"></el-table-column>
                    <el-table-column prop="timeinfo" width="100px"></el-table-column>
                    <el-table-column prop="weekinfo"></el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { weekArray } from "@/const/index"
export default {
    name: "TimeSlot",
    data() {
        return {
            tableData: [],
            weeks: weekArray,
            start: '',
            end: '',
            week: [ '7', '1', '2', '3', '4', '5', '6' ],
            weekIds: [],
            weekNames: [],
            indexIds:[],
            rowIndex: 1,

            forbidTableData: [],
            forbidStart: '',
            forbidEnd: '',
            forbidWeek: [ '7', '1', '2', '3', '4', '5', '6' ],
            forbidWeekIds: [],
            forbidWeekNames: [],
            forbidIndexIds: [],
            forbidRowIndex: 1,

            // timeSlotArray: [],
        }
    },
    created() {
        this.$eventBus.$on('initBasicData', this.initBasicData);
    },
    beforeDestroy() {
        this.$eventBus.$off('initBasicData');
    },
    mounted() {
        // this.$nextTick(function() {
        //     this.weekChange('downloads')
        //     this.weekChange('onoffs')
        //     if(this.editorForm.downloads) {
        //         this.doAddTableData('downloads', this.editorForm.downloads)
        //     }else{
        //         this.editorForm.downloads = []
        //     }
        //     if(this.editorForm.onoffs) {
        //         this.doAddTableData('onoffs', this.editorForm.onoffs)
        //     }else {
        //         this.editorForm.onoffs = []
        //     }
        // })
    },
    computed:{
        timeSlotArray(){
            return this.getTimeArray(0)
        },
        endTimeSlotArray(){
            let index = this.timeSlotArray.findIndex(item => item.value === this.start)
            index = index > -1?index+1:0
            return this.getTimeArray(index)
        },
        forbidEndTimeSlotArray(){
            let index = this.timeSlotArray.findIndex(item => item.value === this.forbidStart)
            index = index > -1?index+1:0
            return this.getTimeArray(index)
        }
    },
    props: {
        editorForm: {
            default:{}
        }
    },
    methods: {
        getTimeArray(index){
            var arr = []
            for(var i = index;i<289;i++){
                var hour = parseInt(i/12)
                var minute = parseInt(i/2) % 6
                minute = minute +''+ i%2 * 5
                if(hour < 10){
                    arr.push({name:'0'+hour+':'+minute,value:'0'+hour+':'+minute})
                } else {
                    arr.push({name:hour+':'+minute,value:hour+':'+minute})
                }
            }
            return arr
        },
        weekChange(type) {
            if(type === 'downloads') {
                this.weekIds = []
                this.weekNames = []
                //先排个序
                const val = this.week.sort()
                for(let i=0; i<=val.length-1; i++){
                    this.weeks.find((item)=>{
                        if(item.value === val[i]){
                            this.weekIds.push(item.value)
                            this.weekNames.push((item.name).replace('星期', ''))
                        }
                    });
                }
            }
            if(type === 'onoffs') {
                this.forbidWeekIds = []
                this.forbidWeekNames = []
                //先排个序
                const val = this.forbidWeek.sort()
                for(let i=0; i<=val.length-1; i++){
                    this.weeks.find((item)=>{
                        if(item.value === val[i]){
                            this.forbidWeekIds.push(item.value)
                            this.forbidWeekNames.push((item.name).replace('星期', ''))
                        }
                    });
                }
            }
        },
        doAddWeekInfo(type) {
            if(type === 'downloads') {
                if(this.tableData.length >= 10) {
                    this.$message.error('最多只能添加10条时间段')
                    return
                }
                if(!this.start) {
                    this.$message.error('请选择开始时间')
                    return
                }
                if(!this.end) {
                    this.$message.error('请选择结束时间')
                    return
                }
                if(this.weekNames.length == 0) {
                    this.$message.error('请选择周期')
                    return
                }
                const today = this.$dateFormat('Y-m-d', new Date())
                const startTime = new Date(today + ' ' + this.start ).getTime()
                const endTime = new Date(today + ' ' + this.end ).getTime()
                if(startTime >= endTime) {
                    this.$message.error('开始时间不能大于结束时间')
                    return
                }
                try {
                    this.tableData.forEach(item => {
                        let tin = item.timeinfo
                        let st = tin.split('-')[0]
                        let ed = tin.split('-')[1]

                        var stTime = new Date(today + ' ' + st ).getTime()
                        var edTime = new Date(today + ' ' + ed ).getTime()

                        let wkArr = item.week.split(',')

                        for(var i = 0;i<wkArr.length;i++) {
                            let wkid = wkArr[i]
                            if(this.weekIds.indexOf(wkid) != -1) {
                                if(startTime < edTime && endTime > stTime){
                                    throw Error()
                                }
                            }
                        }
                    })
                } catch (e) {
                    this.$message.error('添加的时间段与已存在的时间段冲突')
                    return
                }
                let timeinfo = this.start + '-' + this.end
                let weekinfo =  '每周:' +this.weekNames.join('')
                this.tableData.push({ timeinfo: timeinfo, weekinfo: weekinfo, index: this.rowIndex,week: this.weekIds.join(',') })
                this.rowIndex = this.rowIndex + 1
                if(!this.editorForm.downloads){
                    this.editorForm.downloads = []
                }
                this.editorForm.downloads.push({
                    start: this.start,
                    end: this.end,
                    week: this.weekIds.join(',')
                })
             } else if(type === 'onoffs') {
                 if(this.forbidTableData.length >= 10) {
                    this.$message.error('最多只能添加10条时间段')
                    return
                }
                if(!this.forbidStart) {
                    this.$message.error('请选择开始时间')
                    return
                }
                if(!this.forbidEnd) {
                    this.$message.error('请选择结束时间')
                    return
                }
                if(this.forbidWeekNames.length == 0) {
                    this.$message.error('请选择周期')
                    return
                }
                const today = this.$dateFormat('Y-m-d', new Date())
                const startTime = new Date(today + ' ' + this.forbidStart ).getTime()
                const endTime = new Date(today + ' ' + this.forbidEnd ).getTime()
                if(startTime >= endTime) {
                    this.$message.error('开始时间不能大于结束时间')
                    return
                }
                try {
                    this.forbidTableData.forEach(item => {
                        let tin = item.timeinfo
                        let st = tin.split('-')[0]
                        let ed = tin.split('-')[1]

                        var stTime = new Date(today + ' ' + st ).getTime()
                        var edTime = new Date(today + ' ' + ed ).getTime()

                        let wkArr = item.week.split(',')

                        for(var i = 0;i<wkArr.length;i++) {
                            let wkid = wkArr[i]
                            if(this.forbidWeekIds.indexOf(wkid) != -1) {
                                if(startTime < edTime && endTime > stTime){
                                    throw Error()
                                }
                            }
                        }
                    })
                } catch (e) {
                    this.$message.error('添加的时间段与已存在的时间段冲突')
                    return
                }
                let timeinfo = this.forbidStart + '-' + this.forbidEnd
                let weekinfo =  '每周:' +this.forbidWeekNames.join('')
                this.forbidTableData.push({ timeinfo: timeinfo, weekinfo: weekinfo, index: this.rowIndex,week: this.forbidWeekIds.join(',') })
                this.forbidRowIndex = this.forbidRowIndex + 1
                if(!this.editorForm.onoffs){
                    this.editorForm.onoffs = []
                }
                this.editorForm.onoffs.push({
                    start: this.forbidStart,
                    end: this.forbidEnd,
                    week: this.forbidWeekIds.join(',')
                })
             }
        },
        doAddTableData(type, dataArray) {
            dataArray.forEach(item => {
                let timeinfo = item.start + '-' + item.end
                if(type === 'downloads') {
                    this.week = item.week.split(',')
                    this.weekChange('downloads')
                    let weekinfo =  '每周:' + this.weekNames.join('')
                    this.tableData.push({ timeinfo: timeinfo, weekinfo: weekinfo, index: this.rowIndex, week:item.week, type: 'downloads'  })
                    this.rowIndex = this.rowIndex + 1
                } else if( type === 'onoffs') {
                    this.forbidWeek = item.week.split(',')
                    this.weekChange('onoffs')
                    let weekinfo =  '每周:' + this.forbidWeekNames.join('')
                    this.forbidTableData.push({ timeinfo: timeinfo, weekinfo: weekinfo, index: this.forbidRowIndex, week:item.week, type: 'onoffs' })
                    this.forbidRowIndex = this.forbidRowIndex + 1
                }
            })
        },
        getCurrentRow(row, column, event){
            if(row.type === 'downloads') {
                if(this.indexIds.indexOf(row.index) == -1) {
                    this.$refs.table.toggleRowSelection(row, true);
                }else{
                    this.$refs.table.toggleRowSelection(row, false);
                }
            }else if(row.type === 'onoffs') {
                if(this.forbidIndexIds.indexOf(row.index) == -1) {
                    this.$refs.forbidTable.toggleRowSelection(row, true);
                }else{
                    this.$refs.forbidTable.toggleRowSelection(row, false);
                }
            }
        },
        handleSelectionOnoffsChange(val) {
            this.forbidIndexIds = []
            val.forEach(element => {
                this.forbidIndexIds.push(element.index)
            });
        },
        handleSelectionDownloadsChange(val) {
            this.indexIds = []
            val.forEach(element => {
                this.indexIds.push(element.index)
            });
        },
        // 删除当前行
        deleteRow(type) {
            if(type === 'downloads') {
                if(this.indexIds.length < 1) {
                     this.$alert('提示', '请先选择时间段');
                    return
                }
                this.tableData = this.tableData.filter((item)=>{
                    return this.indexIds.indexOf(item.index) == -1;
                });
                this.editorForm.downloads = this.editorForm.downloads.filter((item,index)=>{
                    return this.indexIds.indexOf(index+1) == -1;
                })
                this.indexIds = []
            } else if(type === 'onoffs') {
                if(this.forbidIndexIds.length < 1) {
                    this.$alert('提示', '请先选择时间段');
                    return
                }
                this.forbidTableData = this.forbidTableData.filter((item)=>{
                    return this.forbidIndexIds.indexOf(item.index) == -1;
                });
                this.editorForm.onoffs = this.editorForm.onoffs.filter((item,index)=>{
                    return this.forbidIndexIds.indexOf(index+1) == -1;
                })
                this.forbidIndexIds = []
            }
        },
        // 清空表格
        deleteAll(type) {
            if(type === 'downloads') {
                this.tableData = []
                this.editorForm.downloads = []
                this.rowIndex = 1
             } else if(type === 'onoffs') {
                this.forbidTableData = []
                this.editorForm.onoffs = []
                this.rowIndex = 1
             }
        },

        initBasicData() {
            this.$nextTick(() => {
                this.tableData = []
                this.start = ''
                this.end = ''
                this.indexIds = []
                this.rowIndex = 1

                this.forbidTableData = []
                this.forbidStart = ''
                this.forbidEnd = ''
                this.forbidIndexIds = []
                this.forbidRowIndex = 1

                // this.weekChange('downloads')
                // this.weekChange('onoffs')

                if(this.editorForm.downloads) {
                    this.doAddTableData('downloads', this.editorForm.downloads)
                }
                if(this.editorForm.onoffs) {
                    this.doAddTableData('onoffs', this.editorForm.onoffs)
                }
                //必须放在这个后面，以上初始化用到
                this.week= [ '7', '1', '2', '3', '4', '5', '6' ]
                this.weekChange('downloads')

                this.forbidWeek = [ '7', '1', '2', '3', '4', '5', '6' ]
                this.weekChange('onoffs')
            })
        }
    }
}
</script>
